package stark.app.frame.document.poiexcel;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import stark.app.R;
import stark.common.basic.utils.PermissionUtil;

/**
 * https://github.com/andruhon/android5xlsx
 *
 * poi-ooxml-schemas-3.12-20150511-a.jar
 * poi-3.12-android-a.jar
 */
public class CreateExcelDemoActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
    private static final String TAG = "CreateExcelDemoActivity";
    ArrayAdapter<String> mAdapter ;
    List<String> mNames = new ArrayList<>();
    private String mPath = Environment.getExternalStorageDirectory().getPath() + "/StarkCommon";
    EditText mEtName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_excel_demo);
        mEtName = findViewById(R.id.etName);
        findViewById(R.id.btnCreate).setOnClickListener(mOnClickListener);
        ListView lv = findViewById(R.id.lv);
        mAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,mNames);
        lv.setAdapter(mAdapter);
        lv.setOnItemClickListener(this);
        readFilePermission();

    }

    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mEtName.getText().toString().isEmpty()) {
                Toast.makeText(CreateExcelDemoActivity.this, "请输入表格名称", Toast.LENGTH_SHORT).show();
            } else {
                PermissionUtil.with(CreateExcelDemoActivity.this)
                        .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .request(granted -> {
                            if (granted) {
                                onWriteExcel(mEtName.getText().toString());
                            }
                        });
            }
        }
    };

    public void onWriteExcel(String excelName) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet(WorkbookUtil.createSafeSheetName("mySheet"));
        for (int i=0;i<100;i++) {
            Row row = sheet.createRow(i);
            for(int j=0;j<26;j++) {
                Cell cell = row.createCell(j);
                cell.setCellValue("");
            }
        }
        String fileName = (excelName.contains(".xlsx") || excelName.contains(".xls")) ? excelName : excelName + ".xlsx";
        try {
            File outFile = new File(mPath,fileName);
            if(!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdir();
            }
            if(outFile.exists()){
                Toast.makeText(this, "文件已存在", Toast.LENGTH_SHORT).show();
            }else {
                outFile.createNewFile();
            }
            OutputStream outputStream = new FileOutputStream(outFile.getAbsolutePath());
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            mNames.add(fileName);
            mAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            Log.e(TAG, "onWriteExcel: "+e.toString() );
        }
    }

    public void readFilePermission(){
        PermissionUtil.with(CreateExcelDemoActivity.this)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request(granted -> {
                    if (granted) {
                        readFile();
                    }
                });

    }

    private void readFile() {
        File file = new File(mPath);
        if (file.exists()) {
            File[] fileArr = file.listFiles();
            for(File f:fileArr){
                if(f.isFile()){
                    mNames.add(f.getName());
                }
            }
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = mPath+File.separator+mNames.get(position);
        Intent intent = new Intent(this,ExcelDemoActivity.class);
        intent.putExtra("FilePath",path);//开发项目请将key放入Constants类
        startActivity(intent);
    }
}